#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Common.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"

using namespace LogModule;

namespace SocketModule
{
    const int gbacklog = 8;
    const int defaultsockfd = -1;
    // 模版方法模式
    // 基类socket, 大部分方法，都是纯虚方法
    class Socket
    {
    public:
        ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual bool BindOrDie(uint16_t port) = 0;
        virtual bool ListenOrDie(int backlog) = 0;
        virtual int Connect(const std::string &ip, uint16_t port) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr *pclient) = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &message) = 0;
        virtual void Close() = 0;

    public:
        void BuildTcpSocketMethod(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }
        void BuildTcpClientSocketMethod()
        {
            SocketOrDie();
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
            : _sockfd(defaultsockfd)
        {
        }
        TcpSocket(int sockfd)
            : _sockfd(sockfd)
        {
        }
        void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error!";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
        }

        bool BindOrDie(uint16_t port) override
        {
            InetAddr local("0", port);
            int n = ::bind(_sockfd, local.NetAddrPtr(), local.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error!";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success, sockfd: " << _sockfd;
            return true;
        }

        bool ListenOrDie(int backlog) override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "liisten error!";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success, sockfd: " << _sockfd;
            return true;
        }
        std::shared_ptr<Socket> Accept(InetAddr *pclient) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newfd = ::accept(_sockfd, CONV(peer), &len);
            if (newfd < 0)
            {
                LOG(LogLevel::FATAL) << "accept warning...";
                return nullptr;
            }
            pclient->SetAddr(peer);
            LOG(LogLevel::FATAL) << "accept success!";
            return std::make_shared<TcpSocket>(newfd);
        }

        int Connect(const std::string &ip, uint16_t port)
        {
            InetAddr server(ip, port);
            return ::connect(_sockfd, server.NetAddrPtr(), server.NetAddrLen());
        }
        int Recv(std::string *out) override
        {
            char inbuffer[1024];
            int n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }
        int Send(const std::string &message) override
        {
            int n = ::send(_sockfd, message.c_str(), message.size(), 0);
            return n;
        }

        void Close()
        {
            if (_sockfd > 0)
            {
                close(_sockfd);
            }
        }

    private:
        int _sockfd;
    };
}